//
//  DealViewController.m
//  团购
//
//  Created by 樊荣海 on 15/1/20.
//  Copyright (c) 2015年 樊荣海. All rights reserved.
//

#import "DealViewController.h"

@interface DealViewController () <DPRequestDelegate, SRRefreshDelegate>

@end

@implementation DealViewController {
    
    NSMutableArray *_deals;
    
    SRRefreshView   *_slimeView;
    
    int _page;
    
    
    CoverView *_cover;
    
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (id)init {
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(250, 250);
    layout.minimumLineSpacing = 20; // 每一行之间的间距
    
    return [self initWithCollectionViewLayout:layout];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.collectionView.backgroundColor = globalBgColor;
    
    kAddAllNotes(reloadData)
    
    UISearchBar *search = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
    search.tintColor = globalTintColor;
    search.placeholder = @"请输入商品名";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:search];
    
    TopMenuView *t = [[TopMenuView alloc] init];
    t.contentView = self.view;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:t];
    
    _deals = [NSMutableArray array];
    
    _slimeView = [[SRRefreshView alloc] init];
    _slimeView.delegate = self;
    _slimeView.upInset = 0;
    _slimeView.slimeMissWhenGoingBack = YES;
    _slimeView.slime.bodyColor = [UIColor grayColor];
    _slimeView.slime.lineWith = 1;
    _slimeView.slime.shadowBlur = 4;
    _slimeView.autoresizingMask = self.collectionView.autoresizingMask;
    __unsafe_unretained DealViewController *weakSelf = self;
    _slimeView.block = ^(SRRefreshView *slimeView) {
        [weakSelf reloadData];
    };
    
    [self.collectionView addSubview:_slimeView];
    self.collectionView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    self.collectionView.alwaysBounceVertical = YES;
    
    [self.collectionView registerNib:[UINib nibWithNibName:@"DealCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"DealCell"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"LastCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"LastCell"];
    
    //第一次加载数据
    [self reloadData];
    [MBTool showHUD:@"正在加载..." inView:self.view];
    
}

- (void)reloadData {
    
    NSLog(@"刷新/ 收到城市改变通知");
    self.collectionView.contentOffset = CGPointZero;
    
    _page = 1;
    
    [[DealTool sharedDealTool] dealToolWithPage:_page success:^(NSArray *modelArray) {
        
        
        [MBTool removeHUD];
        [_slimeView endRefresh];
        [_deals removeAllObjects];
        [_deals addObjectsFromArray:modelArray];
        
        [self.collectionView reloadData];
        
        
    } fail:^(NSError *error) {
        
        NSLog(@"error");
        [MBTool removeHUD];
        [MBTool showHUDWithText:@"网络连接错误" inView:self.view Delay:1.5];
        [_slimeView endRefresh];
        
    }];
    
    
}

- (void)viewWillAppear:(BOOL)animated
{
    // 默认计算layout
    [self didRotateFromInterfaceOrientation:0];
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
    
    NSLog(@"willRotateToInterfaceOrientation");
    
    // 1.取出layout
    UICollectionViewFlowLayout *layout = (UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout;
    
    // 2.计算间距
    CGFloat v = 20;
    CGFloat h = 0;
    if (UIInterfaceOrientationIsLandscape(self.interfaceOrientation)) { // 横屏
        h = (self.view.frame.size.width - 3 * 250) / 4;
    } else {
        h = (self.view.frame.size.width - 2 * 250) / 3;
    }
    
    //cell之间的间距
    layout.sectionInset = UIEdgeInsetsMake(v, h, v, h);
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    
    
    return _deals.count==0?0: _deals.count + 1;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.item < _deals.count) {
        static NSString * cellIndexFier = @"DealCell";
        DealCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIndexFier forIndexPath:indexPath];
        if (cell == nil) {
            cell = [[DealCell alloc] init];
        }
        cell.dealModel = _deals[indexPath.item];
        
        return cell;
        
    } else {
        
        NSLog(@"创建了lastcell");
        
        static NSString * cellIndexFier = @"LastCell";
        LastCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIndexFier forIndexPath:indexPath];
        if (cell == nil) {
            cell = [[LastCell alloc] init];
            
        }
        
        cell.page = _page;
        cell.block = ^(NSArray *array){
            
            if (array.count>0) {
                _page++;
                
                [_deals addObjectsFromArray:array];
                [self.collectionView reloadData];
            }
            
        };
        
        return cell;
    }
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (_deals.count == 0) return;
    
    DealModel *deal = _deals[indexPath.item];
    NSLog(@"点击内容: %@", deal.desc);
    if (_cover == nil) {
        _cover = [CoverView coverWithTarget:self action:@selector(tapClick)];
        _cover.frame = self.navigationController.view.bounds;
    }
    _cover.alpha = 0;
    [UIView animateWithDuration:0.5 animations:^{
        [_cover resetAlpha];
    }];
    [self.navigationController.view addSubview:_cover];
    
    DealDetailViewController * detail = [[DealDetailViewController alloc] init];
    detail.dealModel = deal;
    
    BaseNavigationController *navi = [[BaseNavigationController alloc] initWithRootViewController:detail];
    
    detail.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"btn_nav_close.png" highlightedIcon:@"btn_nav_close_hl.png" target:self action:@selector(tapClick)];
    
    navi.view.frame = CGRectMake(_cover.frame.size.width, 0, DetailW, _cover.frame.size.height);
    navi.view.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleLeftMargin;
    
    [self.navigationController.view addSubview:navi.view];
    [self.navigationController addChildViewController:navi];
    
    
    [UIView animateWithDuration:1 animations:^{
        CGRect rect = navi.view.frame;
        rect.origin.x -= DetailW;
        navi.view.frame = rect;
    }];
    
}

- (void)tapClick {
    
    
    BaseNavigationController *navi  = [self.navigationController.childViewControllers lastObject];
    
    [UIView animateWithDuration:0.5 animations:^{
        _cover.alpha = 0;
        CGRect rect = navi.view.frame;
        rect.origin.x += DetailW;
        navi.view.frame = rect;
    }completion:^(BOOL finished) {
        [_cover removeFromSuperview];
        [navi.view removeFromSuperview];
        [navi removeFromParentViewController];//[重要]
    }];
    
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [_slimeView scrollViewDidScroll];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [_slimeView scrollViewDidEndDraging];
}

#pragma mark - slimeRefresh delegate

- (void)slimeRefreshStartRefresh:(SRRefreshView *)refreshView
{
    
}

@end
